import Vue from 'vue';
import Vuex from 'vuex'

Vue.use(Vuex)


// 初始化时用sessionStore.getItem('token'),这样子刷新页面就无需重新登录
const state = {
    user: window.localStorage.getItem('username'),
    id: window.localStorage.getItem('id'),
    token: window.localStorage.getItem('token'),
    activeIndex: window.localStorage.getItem('activeIndex'),
    rights: window.localStorage.getItem('rights') == "true" ? true : false,
    area: window.localStorage.getItem('area')
}

const mutations = {
    //将token保存到sessionStorage里，token表示登陆状态
    SET_TOKEN: (state, data) => {
        state.token = data
        window.localStorage.setItem('token', data)
    },
    //获取用户名
    SET_USER: (state, data) => {
        // 把用户名存起来
        state.user = data
    },
    //获取id
    SET_ID: (state, data) => {
        state.id = data
    },
    //获取权限
    SET_RIGHTS: (state, data) => {
        state.rights = data
    },
    //获取区域    
    SET_AREA: (state, data) => {
        state.area = data
    },
    //登出
    LOGOUT: (state) => {
        // 登出的时候要清除token
        state.token = null
        state.user = null
        state.activeIndex = null;
        window.localStorage.removeItem('token')
        window.localStorage.removeItem('username')
        window.localStorage.removeItem('activeIndex')
        window.localStorage.removeItem('id')
        window.localStorage.removeItem('rights')
        window.localStorage.removeItem('area')
    },
    SET_PAGE: (state, data) => {
        state.activeIndex = data;
    },
    SET_INFO_TO_SESSION: (state) => {
        window.localStorage.setItem('username', state.user);
        window.localStorage.setItem('activeIndex', state.activeIndex);
        window.localStorage.setItem('id', state.id);
        window.localStorage.setItem('rights', state.rights);
        window.localStorage.setItem('area', state.area);
    },
}

const actions = {
    setToken: (context, data) => {
        context.commit('SET_TOKEN', data)
    },
    setUser: (context, data) => {
        context.commit('SET_USER', data)
    },
    setID: (context, data) => {
        context.commit('SET_ID', data)
    },
    setRights: (context, data) => {
        context.commit('SET_RIGHTS', data)
    },
    setArea: (context, data) => {
        context.commit('SET_AREA', data)
    },
    logout: (context) => {
        context.commit('LOGOUT')
    },
    setPage: (context, data) => {
        context.commit('SET_PAGE', data)
    },
    setInfoToSession: (context) => {
        context.commit('SET_INFO_TO_SESSION')
    }
}

export default new Vuex.Store({
    state,
    mutations,
    actions
})
